package com.taro.blog.servlet;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.taro.blog.model.ArticleDetailResult;
import com.taro.blog.model.User;
import com.taro.blog.service.ArticleService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet("/article-detail.json")
public class ArticleDetailJsonServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 1. 从请求参数中获取 aid
        req.setCharacterEncoding("utf-8");
        String aidString = req.getParameter("aid");
        // TODO: 参数合法性问题
        int aid = Integer.parseInt(aidString);

        User currentUser = null;
        HttpSession session = req.getSession(false);
        if (session != null) {
            currentUser = (User) session.getAttribute("currentUser");
        }

        // currentUser == null;    说明用户没有登录

        // 构造一个结果对象
        // currentUser
        // articleCount
        // typeCount
        // article
        // servlet     service        dao
        ArticleService articleService = new ArticleService();
        ArticleDetailResult result = articleService.detail(currentUser, aid);

        // 把对象变成 JSON 字符串
        ObjectMapper objectMapper = new ObjectMapper();
        String jsonString = objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(result);

        // 响应这个 jsonString
        resp.setCharacterEncoding("utf-8");
        resp.setContentType("application/json");
        resp.getWriter().println(jsonString);
    }
}
